const fs = require('fs');
const path = require('path');
const {spawn} = require('child_process');

console.log('参数列表', process.argv)
const command = process.argv[2];
console.log("执行命令:", command)
// 获取命令行参数
const envArg = process.argv[3];
if (!envArg) {
    console.error('请提供环境参数!');
    process.exit(1);
}
// 获取配置文件,开发模式获取env_dev.js,打包模式虎丘env_build.js
const envFile = command === 'dev' ? '../envs/env_dev.js' : '../envs/env_build.js';
console.log(`从${envFile}获取配置文件`)
const envConfig = require(envFile);

// 查找匹配的环境配置
const targetEnv = envConfig.envs.find(env => env.code === envArg);
if (!targetEnv) {
    console.error(`未找到环境 ${envArg} 的配置!`);
    process.exit(1);
}

// 生成环境变量内容
const envContent = `VUE_APP_BASE_URL=${targetEnv.url}
VUE_APP_ENV_NAME=${targetEnv.name}`;

// 写入到 .env.local 文件
fs.writeFileSync(path.resolve(__dirname, '../.env.local'), envContent);

console.log(`已设置环境变量:
VUE_APP_BASE_URL=${targetEnv.url}
VUE_APP_ENV_NAME=${targetEnv.name}`);

// 执行 vue-cli-service serve
// const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const npm = 'vue-cli-service'

const commands = []
if (command === 'dev') {
    commands.push('serve')
}
if (command === 'build') {
    commands.push('build')
    // 如果targetEnv存在dist目录,增加dist参数
    if (targetEnv.dist) {
        commands.push(`--dest=${targetEnv.dist}`);
    }
}
console.log('最终命令', commands)
spawn(npm, commands, {
    stdio: 'inherit',
    shell: true
}); 